<template>
    <div class="dashboard_wrapper flex-column">
        <div id="fly" class="dashboard_amap"></div>
    </div>
</template>
<script>
export default {
    name: 'FlyMap',
    dicts: ['city'],
    data() {
        return {
            map: null,
            path: [],
            pathSimplifierIns: null,
            //   巡航器移动速度
            moveSpeed: 30000 * 5,
            //   巡航器
            navg: null,
            //   巡航是否结束
            isEnd: false
        };
    },
    watch: {
        'dict.city': function(cityList) {
            if (cityList && cityList.length) {
                this.path = [];
                cityList.map(async (city, index) => {
                    let { dictValue } = city;
                    let cityItemBox = dictValue.split('/');
                    let province = cityItemBox[0];
                    let cityName = cityItemBox[1];
                    let result = await this.getCityLocation(cityName);
                    this.drawLine(cityName, result);
                });
            }
        }
    },
    mounted() {
        this.initMap();
    },
    destroyed() {
        this.map.destroy();
        this.map = null;
    },
    methods: {
        initMap() {
            this.map = new AMap.Map('fly', {
                layers: [
                    // 卫星
                    new AMap.TileLayer.Satellite(),
                    // 路网
                    new AMap.TileLayer.RoadNet()
                ],
                zoom: 5
            });
        },
        drawLine(cityName, toLocation) {
            let that = this;
            //   清除轨迹路线
            if (window.pathSimplifierIns) {
                this.pathSimplifierIns = null;
            }
            AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], function(PathSimplifier, $) {
                if (!PathSimplifier.supportCanvas) {
                    alert('当前环境不支持 Canvas！');
                    return;
                }
                that.pathSimplifierIns = new PathSimplifier({
                    zIndex: 100,
                    //autoSetFitView:false,
                    map: that.map, //所属的地图实例
                    getPath: function(pathData, pathIndex) {
                        return pathData.path;
                    },
                    getHoverTitle: function(pathData, pathIndex, pointIndex) {
                        if (pointIndex >= 0) {
                            //point
                            return pathData.name + '，点：' + pointIndex + '/' + pathData.path.length;
                        }
                        return pathData.name;
                        // return pathData.name + '，点数量' + pathData.path.length
                    },
                    renderOptions: {
                        renderAllPointsIfNumberBelow: 100 //绘制路线节点，如不需要可设置为-1
                    }
                });
                window.pathSimplifierIns = that.pathSimplifierIns;
                var start = [120.21376, 30.21234]; //总部位置
                // let list = that.countRoadStation(start,toLocation);
                //设置数据
                that.pathSimplifierIns.setData([
                    {
                        name: cityName,
                        path: [start, toLocation]
                    }
                ]);
                that.trackFlag = true;
                var navg = that.pathSimplifierIns.createPathNavigator(0, {
                    loop: true, //循环播放
                    speed: 300 //巡航速度，单位千米/小时-默认70，动态设置
                    // pathNavigatorStyle: {
                    //     width: 48,
                    //     height: 48,
                    //     //使用图片
                    //     content: PathSimplifier.Render.Canvas.getImageContent('//webapi.amap.com/theme/v1.3/images/newpc/way_btn2.png', onload, onerror),
                    //     autoRotate: true,
                    //     lineJoin: 'round',
                    //     lineWidth: 2,
                    //     fillStyle: '#087EC4',
                    //     strokeStyle: '#116394',
                    //     // //经过路径的样式
                    //     pathLinePassedStyle: {
                    //         lineWidth: 6,
                    //         strokeStyle: 'black',
                    //         dirArrowStyle: {
                    //             stepSpace: 15,
                    //             strokeStyle: 'red'
                    //         }
                    //     }
                    // }
                });
                navg.on('move', function() {
                    let idx = navg.getCursor().idx; //走到了第几个点
                    let tail = navg.getCursor().tail; //至下一个节点的比例位置
                    let totalIdx = idx + tail;
                    var distance = Math.round(AMap.GeometryUtil.distance(start, toLocation) / 100);
                    // if (idx === list.length - 1) {
                    //     that.isPlay = 1
                    //     that.percentage = 100
                    // } else {
                    //     // 根据走过的距离计算进度
                    //     that.percentage = Math.round(
                    //         (this.getMovedDistance() / 1000 / distance) * 100
                    //     )
                    //     //   根据走过的点数计算进度
                    //     //   that.percentage = parseInt(
                    //     //     (totalIdx / that.dataList.length) * 100
                    //     //   )
                    // }
                    // 根据走过的距离计算进度
                    that.percentage = Math.round((this.getMovedDistance() / 1000 / distance) * 100);
                    that.latlng = [navg.getPosition().lat, navg.getPosition().lng];
                });
                that.navg = navg;
                that.navg.start();
                that.navg.setSpeed(that.moveSpeed);
                that.map.setZoom(6);
            });
        },
        getCityLocation(city) {
            return new Promise((resolve, reject) => {
                AMap.plugin('AMap.DistrictSearch', () => {
                    var districtSearch = new AMap.DistrictSearch({
                        // 关键字对应的行政区级别，共有5种级别
                        level: 'province',
                        // 是否显示下级行政区级数，1表示返回下一级行政区
                        subdistrict: 0,
                        // 返回行政区边界坐标点
                        extensions: 'all'
                    });

                    districtSearch.search(city, (status, result) => {
                        // 查询成功时，result即为对应的行政区信息
                        if (status == 'complete') {
                            let { districtList } = result;
                            let { center } = districtList[0];
                            let location = [center.lng, center.lat];
                            resolve(location);
                        }
                    });
                });
            });
        },
        //计算沿路的几个点
        countRoadStation(start, end) {
            let center = [(start[0] + end[0]) / 2, (start[1] + end[1]) / 2];
            let half = [(start[0] + center[0]) / 2, (start[1] + center[1]) / 2];
            let part = [(half[0] + end[0]) / 2, (half[1] + end[1]) / 2];
            return [start, half, center, part, end];
        }
    }
};
</script>
<style lang="scss" scoped>
.dashboard_wrapper {
    width: 100%;
    height: 100%;
    .dashboard_amap {
        flex: 1;
        & > ::v-deep .el-vue-amap {
            display: flex;
            flex: 1;
        }
    }
}
</style>
